package org.csu.linkgame.service.ClassForDoubleGame;

import org.csu.linkgame.domain.User;

import java.io.*;
import java.net.Socket;
import java.util.List;

public class SocketThread2 implements Runnable{
    public Socket socket;
    public dgServiceImpl canvas;
    public ObjectInputStream is = null;
    User user;
    public SocketThread2(Socket socket,dgServiceImpl canvas,ObjectInputStream is){
        this.socket = socket;
        this.canvas = canvas;
        this.is = is;
    }
    public SocketThread2(Socket socket,dgServiceImpl canvas,User user){
        this.socket = socket;
        this.canvas = canvas;
        this.user = user;
    }

    @Override
    public void run() {
        // 判断是否接受了敌人的信息
        int receiveEnemyFlag = 0;
        System.out.println("用户此时向服务器传递user信息"+user.getUsername());
        ObjectOutputStream os = null;
        try {
            os = new ObjectOutputStream(this.socket.getOutputStream());
            os.writeObject(user);
            os.flush();
        }catch (Exception o){
            o.printStackTrace();
        }
        while(true){
            ObjectInputStream is = null;
            try {
                is = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
                Object obj = is.readObject();
                if(obj instanceof User){
                    if(receiveEnemyFlag==0){
                        userGameView.enemy = (User) obj;
                        System.out.println("这里是Client端，接受到了敌人信息:"+userGameView.enemy.getUsername());
                        System.out.println("用户此时向服务器传递user信息"+user.getUsername());
                        os = new ObjectOutputStream(this.socket.getOutputStream());
                        os.writeObject(user);
                        os.flush();
                        receiveEnemyFlag=1;
                    }
                }else{
                    List<dgPoint> path = (List<dgPoint>)obj;
                    System.out.println("这里是Client端,接收到了服务端传来的path:"+path);
                    canvas.drawLine(path);
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
